﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Threading;
using Libmpc;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace StudybotWPF
{
    class IRCclass
    {
        private string nickname, server, channel;
        private int port = 6667;
        NetworkStream netstream;
        TcpClient irc;
        StreamReader networkreader;
        StreamWriter networkwriter;

        Libmpc.Mpc muziekserver = new Mpc();
        MpcConnection muziekconnectie;
        System.Net.IPEndPoint iptest;

        //connectie met MySQLDB
        string connStr = "server=localhost;user=root;database=test;port=3306;";//password=;";
        MySqlConnection conn;

        public bool connect(string NicknameFromTextbox, string ServerFromTextbox, string ChannelFromTextbox)
        {
            //sla nickname en al op
            nickname = NicknameFromTextbox;
            server = ServerFromTextbox;
            channel = ChannelFromTextbox;
            
            try
            {
                //start irc connectie
                irc = new TcpClient(server, port);
                netstream = irc.GetStream();
                networkreader = new StreamReader(netstream);
                networkwriter = new StreamWriter(netstream);

                //start mpc connectie
                var addresses = System.Net.Dns.GetHostAddresses("dragonrebel.no-ip.org");
                iptest = new System.Net.IPEndPoint(addresses[0], 6600);
                muziekconnectie = new MpcConnection(iptest);
                muziekserver.Connection = muziekconnectie;

                //start mySQLDB connectie
                conn = new MySqlConnection(connStr);
            }
            catch
            {
                return false;
            }
            //identificeer en kies nickname
            networkwriter.WriteLine("USER {0} {0} {0} :{1}", nickname, nickname);
            networkwriter.Flush();
            networkwriter.WriteLine("NICK {0}", nickname);
            networkwriter.Flush();

            //neem een kleine pauze om zeker te zijn
            System.Threading.Thread.Sleep(500);
            //join channel
            networkwriter.WriteLine("JOIN {0}", channel);
            networkwriter.Flush();
            System.Threading.Thread.Sleep(100);
            //groet anderen :p
            networkwriter.WriteLine("PRIVMSG {0} :Hello all, I am studybot", channel);
            networkwriter.WriteLine("PRIVMSG {0} :Voor mpc commando's, typ '!mpc help'", channel);
            networkwriter.Flush();         
            

            return true;

        }
        public void reading()
        {
            //Deze method word opgeroepen in een tweede thread, hierdoor bokt het programma niet, hij blijft gewoon constant in de while lus.
            string line;
            while (1 == 1)
            {
                //lees in
                line = networkreader.ReadLine();
                //als er iets ingelezen is gaan we door
                if (line != null)
                {
                    //zet in de tekstbox alles dat we inlezen (handig voor debug)
                    schrijven(line);
                    //split de line
                    string[] splittedline = line.Split(' ');
                    //check op pings, respond with pong
                    if (splittedline[0] == "PING")
                    {
                        //roep de method op die het schrijven doet, geef hiervoor de juiste code mee (bv, 0 = ping)
                        talking(0, line);
                    }
                    else
                    {
                        //als er genoeg delen zijn, check wat het derde deel is. In dit deel zit normaal alles wat je vant tekst ziet.
                        if (splittedline.Length >= 4)
                        {
                            switch (splittedline[3])
                            {
                                case ":!studybot": talking(1, line);
                                    break;
                                case ":!mpc": talking(2, splittedline[4]);
                                    break;
                                case ":!sql": talking(3, line);
                                    break;
                            }
                        }

                    }

                    
                }
            }
        }
        //delegate voor schrijven naar tekstbox
        public event writelinetoconsole schrijven;
        public delegate void writelinetoconsole(string whatwehavetowrite);

        public void talking(int code, string line)
        {
            switch(code)
            {
                    //stuur pong indien gepingt
                case 0: networkwriter.WriteLine("PONG" + line.Substring(4));
                        networkwriter.Flush();
                        schrijven("PONG" + line.Substring(4));
                    break;
                    //test commando
                case 1: networkwriter.WriteLine("PRIVMSG {0} :Yes, I am here.", channel);
                    networkwriter.Flush();
                    schrijven("PRIVMSG " + channel+ " :Yes, I am here.");
                    break;
                    // mpc commando's
                case 2:
                    switch (line)
                    {
                        case "help"://Vraag alle comando's op
                            {
                                networkwriter.WriteLine("PRIVMSG {0} :----------De geldige commando's zijn: -------------", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!mpc play", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!mpc pauze", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!mpc next", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!mpc prev", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!mpc song", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :----------Einde commando's ------------------------", channel);
                                break;
                            }
                        case "play"://play
                            {
                                muziekserver.Play();
                                networkwriter.WriteLine("PRIVMSG {0} :" + "Play", channel);
                                break;
                            }
                        case "pauze"://pauze
                            {
                                muziekserver.Pause(true);
                                networkwriter.WriteLine("PRIVMSG {0} :" + "Pauze", channel);
                                break;
                            }
                        case "next"://next
                            {
                                muziekserver.Next();
                                networkwriter.WriteLine("PRIVMSG {0} :" + "Next", channel);
                                break;
                            }
                        case "prev"://prev
                            {
                                muziekserver.Previous();
                                networkwriter.WriteLine("PRIVMSG {0} :" + "Previous", channel);
                                break;
                            }
                        case "song"://song
                            {
                                MpdFile HuidigLied = muziekserver.CurrentSong();
                                networkwriter.WriteLine("PRIVMSG {0} :" + HuidigLied.Artist + " - " + HuidigLied.Title, channel);
                                break;
                            }                         
                    }
                    networkwriter.Flush();//schrijf naar IRC
                    break;
                case 3:
                    line = line.Substring(line.IndexOf(':') + 1);
                    line = line.Substring(line.IndexOf(':') + 1);
                    
                    
                    string split = line.Split(' ')[1];
                    switch (split)
                    {
                        case "help"://Vraag alle comando's op
                            {
                                networkwriter.WriteLine("PRIVMSG {0} :----------De geldige commando's zijn: -------------", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!sql write [text]", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :!sql read", channel);
                                networkwriter.WriteLine("PRIVMSG {0} :----------Einde commando's ------------------------", channel);
                                break;
                            }
                        case ("write"):
                            {
                                line = line.Substring(line.IndexOf(' ') + 1);
                                if (line.Contains('{') || line.Contains('}') || line.Contains('\\'))
                                {
                                    networkwriter.WriteLine("PRIVMSG {0} :PROBEER ME BOT NI TE KLOOTN!!!!!!!", channel);
                                }
                                else
                                {
                                    writeDB("tabel1", "text", line.Substring(split.Length));
                                }
                            }
                            break;
                        case ("read"):
                            {
                                readDB("tabel1");
                            }
                            break;
                    }
                    networkwriter.Flush();//schrijf naar IRC
                    break;
            }

        }

        public void writeDB(string tabel, string kolommen, string values) //schrijf in DB
        {
            conn.Open(); //open connectie
            string sql = "INSERT INTO " + tabel + " (" + kolommen + ") VALUES ('" + values + "')"; //maak query
            MySqlCommand cmd = new MySqlCommand(sql, conn); //maak sqlCommand
            cmd.ExecuteNonQuery();//voer command uit

            conn.Close(); //sluit connectie
        }
        public void readDB(string tabel) //lees in DB
        {
            conn.Open(); //open connectie
            string sql = "SELECT * FROM " + tabel ; //maak query
            MySqlCommand cmd = new MySqlCommand(sql, conn); //maak sqlCommand
            MySqlDataReader rdr = cmd.ExecuteReader();//voer command uit
            schrijven("DATABASE GELEZEN, START MET SCHRIJVEN NAAR BUFFER");
            networkwriter.WriteLine("PRIVMSG {0} :" + " ----------------------------------------------------------------------- " , channel);
            while (rdr.Read())
            {
                networkwriter.WriteLine("PRIVMSG {0} :" + rdr[0] + " -- " + rdr[1], channel);
            }
            networkwriter.WriteLine("PRIVMSG {0} :" + " ----------------------------------------------------------------------- ", channel);
            rdr.Close();
            conn.Close(); //sluit connectie
            schrijven("BUFFER GESCHREVEN, START FLUSHEN");
            networkwriter.Flush();//schrijf naar IRC
            schrijven("GEDAAN MET FLUSHEN");
        }
    }
}
